package org.dfl.plugin.editor.actions;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.dfl.core.data.History;
import org.dfl.core.data.IODataManager;
import org.dfl.core.data.Token;
import org.dfl.core.model.Place;
import org.dfl.messages.Messages;
import org.dfl.plugin.DflPlugin;
import org.dfl.plugin.ProjectConstraints;
import org.dfl.plugin.dialogs.DialogsManager;
import org.dfl.plugin.editor.model.DflDiagram;
import org.dfl.plugin.editor.model.PlaceModelElement;
import org.dfl.plugin.utils.WorkbenchUtil;
import org.eclipse.core.resources.IProject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPart;

/**
 * save the flow state in a file action 
 * @author Piotr Wlodarczyk
 *
 */
public class SaveAllTokensAction extends org.eclipse.gef.ui.actions.SelectionAction {
	public static final String ACTION_ID = "SaveAllTokensAction"; //$NON-NLS-1$
	private DflDiagram diagram;

	public SaveAllTokensAction(IWorkbenchPart part, DflDiagram diagram) {
		super(part);
		this.diagram = diagram;
		setId(ACTION_ID);
		setImageDescriptor(DflPlugin.getImageDescriptor("icons/eclipse/saveall.gif")); //$NON-NLS-1$
		setHoverImageDescriptor(getImageDescriptor());
		setText(Messages.SaveAllTokensAction_0);
		setToolTipText(Messages.SaveAllTokensAction_0);
	}

	protected boolean calculateEnabled() {
		return (diagram!=null && diagram.isRunnning());
	}

	public void run() {
		synchronized (DflPlugin.class) {
			Map<String, Collection<Token>> tokensMap = new HashMap<String, Collection<Token>>();
			Set<PlaceModelElement> places = diagram.getPlaces();
			for (PlaceModelElement pme : places) {
				Collection<Token> tokens = getPlaceTokens(pme.getPlace());
				if (!tokens.isEmpty()) {
					tokensMap.put(pme.getPlace().getId(), tokens);
				}
			}
			if (tokensMap.isEmpty()) {
				DialogsManager.openErrorDialog(Messages.SaveAllTokensAction_2);
			} else {
				saveTokens(tokensMap);
			}
		}
	}

	private Collection<Token> getPlaceTokens(Place place) {
		Collection<Token> tokens = new ArrayList<Token>();
		Map<History, Collection<Token>> placeHistoryMap = place.getHistoryDataMap();
		Set<History> histories = placeHistoryMap.keySet();
		for(History history : histories){
			tokens.addAll(placeHistoryMap.get(history));
		}
		return tokens;
	}

	private void saveTokens(Map<String,Collection<Token>> tokens) {
		FileDialog dlg = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE);
        
		IProject project = WorkbenchUtil.getCurrentProject();
		String projectPath = project.getLocation().toFile().getAbsolutePath();
		if(new File(projectPath + ProjectConstraints.PROJECT_DIR_STATES).exists()){
			dlg.setFilterPath(projectPath + ProjectConstraints.PROJECT_DIR_STATES);
		}else{
			dlg.setFilterPath(projectPath);
		}
		
		IEditorPart editor = WorkbenchUtil.getActiveEditor();
		String prefix = editor.getEditorInput().getName().replace(".dfl", "")+"_fs_"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
		prefix += String.format(Messages.FlowRunner_outputFileFormat,  new GregorianCalendar());
		
        // Change the title bar text
        dlg.setText(Messages.SaveAllTokensAction_3);
        dlg.setFileName(prefix+".xml"); //$NON-NLS-1$
		
     // null if user cancels
        String fileName = dlg.open();
        if (fileName != null) {
        	if(new File(fileName).exists() && !DialogsManager.openOkCancelDialog(Messages.SaveAllTokensAction_9,Messages.SaveAllTokensAction_10)){
        		return;
        	}
        	try {
        		IODataManager.saveTokens(fileName,tokens);
        		WorkbenchUtil.refreshProject(project);
			} catch (Exception e) {
				DialogsManager.openErrorDialog(e);
			}
        }
	}
}
